from rest_framework.decorators import api_view
from django.conf import settings
from django.db import connections
from rest_framework import exceptions

from libs.simple_responses import api_success
from libs.decorators import required_query_parameters


@api_view(['GET'])
def dbs(request):
    dbs = settings.DATABASES.keys()
    items = [{'label': item, 'key': item, 'value': item} for item in dbs]
    data = {
        'total': len(items),
        'items': items
    }
    return api_success(data=data)


@api_view(['GET'])
@required_query_parameters(['db'])
def tables(request):
    db_name = request.query_params.get('db')
    if db_name not in settings.DATABASES.keys():
        raise exceptions.ParseError('无效db')
    tables = []
    with connections[db_name].cursor() as cursor:
        cursor.execute("SHOW TABLES;")
        tables = cursor.fetchall()

    items = [{'label': item[0], 'key': item[0], 'value': item[0]} for item in tables]
    data = {
        'total': len(items),
        'items': items
    }
    return api_success(data=data)


@api_view(['GET'])
@required_query_parameters(['db', 'table'])
def columns(request):
    db_name = request.query_params.get('db')
    table_name = request.query_params.get('table')
    if db_name not in settings.DATABASES.keys():
        raise exceptions.ParseError('无效db')

    fields = []
    with connections[db_name].cursor() as cursor:
        cursor.execute(f"DESCRIBE {table_name};")
        fields = cursor.fetchall()

    items = [{'label': item[0], 'key': item[0], 'value': item[0]} for item in fields]
    data = {
        'total': len(items),
        'items': items
    }
    return api_success(data=data)
